package com.gr3g.dev.learndraw.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;

import android.content.Context;
import android.util.Log;

import com.gr3g.dev.learndraw.model.store.Score;

/** @author Gregory Tardivel */
public final class ScoresLoader {

    /** Fichier de sauvegarde. */
    private static final String FILE = "modeles.score";

    /** Sauvegarde des scores.
     * @param context
     * @param score
     * @throws IOException */
    public static void save(final Context context, final Score score)
            throws IOException {
        final FileOutputStream fos = context.openFileOutput(FILE,
                Context.MODE_PRIVATE);
        final ObjectOutputStream os = new ObjectOutputStream(fos);
        os.writeObject(score);
        os.close();
    }

    /** Chargement des scores.
     * @param context
     * @return
     * @throws StreamCorruptedException
     * @throws IOException
     * @throws ClassNotFoundException */
    public static Score load(final Context context)
            throws StreamCorruptedException, IOException,
            ClassNotFoundException {
        Score retour = null;
        try {
            final FileInputStream fis = context.openFileInput(FILE);
            final ObjectInputStream is = new ObjectInputStream(fis);
            retour = (Score) is.readObject();
            is.close();
        } catch (final FileNotFoundException exc) {
            // Fichier inexistant : premier acces
            Log.i("ScoresLoader", "Fichier de scores introuvable");
        }
        if (retour == null) {
            retour = new Score();
        }
        return retour;
    }
}
